package com.jule.teenpatti.mail.network.protocol.reqs;

import JoloProtobuf.AuthSvr.JoloAuth;
import com.alibaba.fastjson.JSONObject;
import com.jule.core.common.log.LoggerUtils;
import com.jule.core.jedis.StoredObjManager;
import com.jule.teenpatti.base.enums.ErrorCodeEnum;
import com.jule.teenpatti.base.enums.RedisChannel;
import com.jule.teenpatti.mail.dao.DBUtil;
import com.jule.teenpatti.mail.dao.bean.MailAttachmentConfigModel;
import com.jule.teenpatti.mail.dao.bean.MailUserModel;
import com.jule.teenpatti.mail.model.UserMailMap;
import com.jule.teenpatti.mail.network.protocol.ClientReq;
import com.jule.teenpatti.mail.network.protocol.acks.JoloAuth_MailAwardAck_600023;
import com.jule.teenpatti.mail.service.MailConfigService;
import com.jule.teenpatti.mail.service.MailService;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class JoloAuth_MailAwardReq_600023 extends ClientReq {
    public JoloAuth_MailAwardReq_600023(int functionId) {
        super(functionId);
    }

    private JoloAuth.JoloAuth_MailAwardReq req;

    @Override
    public void readPayLoadImpl(ByteBuf buf) throws Exception {
        byte[] blob = new byte[buf.readableBytes()];
        buf.readBytes(blob);
        req = JoloAuth.JoloAuth_MailAwardReq.parseFrom(blob);
    }

    @Override
    public void processImpl() throws Exception {
        log.debug("收到消息-> " + functionId + ", reqNum-> " + header.reqNum + ", req->" + req.toString());
        JoloAuth.JoloAuth_MailAwardAck.Builder ack = JoloAuth.JoloAuth_MailAwardAck.newBuilder();
        ack.addAllMailIds(req.getMailIdList()).setResult(1).setUserId(req.getUserId());
        String userId = req.getUserId();
        List<Long> mailIds = req.getMailIdList();
        try {
            //获取邮件
            UserMailMap userMailMap = MailService.getInstance().getByUserId(userId);
            Iterator<MailUserModel> iterator = userMailMap.getMailMap().values().iterator();
            Map<String, JoloAuth.JoloAuth_MailAwardInfo.Builder> mails = new HashMap();
            while (iterator.hasNext()) {
                MailUserModel model = iterator.next();
                if (mailIds.contains(model.getId())) {
                    getAtt(userId, model, ack,mails);
                    DBUtil.delMailUser(model.getId());
                    iterator.remove();
                }
            }
            MailService.getInstance().saveUserMailMap(userId,userMailMap);
            for(JoloAuth.JoloAuth_MailAwardInfo.Builder ma : mails.values()){
                ack.addMailRewards(ma);
            }
            ctx.writeAndFlush(new JoloAuth_MailAwardAck_600023(ack.build(), header));
        } catch (Exception ex) {
            ack.setResult(0);
            ack.setResultMsg(ErrorCodeEnum.GAME_50002_2.getCode());
            ctx.writeAndFlush(new JoloAuth_MailAwardAck_600023(ack.build(), header));

            log.error(ex.getMessage(), ex);
        }
    }

    private void getAtt(String userId, MailUserModel mail, JoloAuth.JoloAuth_MailAwardAck.Builder ack,
                        Map<String, JoloAuth.JoloAuth_MailAwardInfo.Builder> mails) {
        Map<Integer, MailAttachmentConfigModel> map = MailConfigService.getInstance().getMailAttMap(mail.getMailConfigId());
        if (map != null) {
            Iterator<MailAttachmentConfigModel> iter = map.values().iterator();
            while (iter.hasNext()) {
                MailAttachmentConfigModel attModel = iter.next();
                JoloAuth.JoloAuth_MailAwardInfo.Builder awardInfo = mails.get("" + attModel.getItem_id());
                if(awardInfo == null){
                    awardInfo = JoloAuth.JoloAuth_MailAwardInfo.newBuilder();
                    awardInfo.setItemId("" + attModel.getItem_id());
                    awardInfo.setName(attModel.getName());
                    awardInfo.setNum(attModel.getNumber());
                    awardInfo.setType(attModel.getType());
                    awardInfo.setUrl(attModel.getUrl());
                    mails.put(awardInfo.getItemId()+"",awardInfo);
                }else{
                    awardInfo.setNum(awardInfo.getNum() + attModel.getNumber());
                }
//                JoloAuth.JoloAuth_MailAwardInfo.Builder awardInfo = JoloAuth.JoloAuth_MailAwardInfo.newBuilder();
//                awardInfo.setItemId("" + attModel.getItem_id());
//                awardInfo.setName(attModel.getName());
//                awardInfo.setNum(attModel.getNumber());
//                awardInfo.setType(attModel.getType());
//                awardInfo.setUrl(attModel.getUrl());
//                mailAwards.add(awardInfo.build());
                if (attModel.getType() == 1) {
                    JSONObject js = new JSONObject();
                    js.put("userId", userId);
                    double feedback = Double.valueOf(attModel.getNumber());
                    js.put("money", feedback);
                    StoredObjManager.publish(js.toString(), RedisChannel.MAIL_ATTACHMENT.getChannelName());
                    LoggerUtils.mailLog.info("mail award " + js.toString());
                }
                MailService.getInstance().addAwardRecord(userId, mail, attModel);
            }
//            ack.addAllMailRewards(mailAwards);
        }
    }
}
